package com.example.gomi.intelligentcitypipe.DAO;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by GoMi on 16/7/1.
 */
public class PipeInfoHelper {

    private static PipeInfoHelper ourInstance = null;
    private static Context mContext;

    public static PipeInfoHelper getInstance() {
        if (ourInstance == null) {
            ourInstance = new PipeInfoHelper();
        }
        return ourInstance;
    }

    private Dao<PipeInfo, Integer> mPipeInfoDao = null;

    private DataBaseHelper_ormlite databaseHelper = null;

    private PipeInfoHelper() {
        open();
    }

    public void open() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(mContext, DataBaseHelper_ormlite.class);
        }
        try {
            mPipeInfoDao = databaseHelper.getPipeInfoDao();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static void closeHelper() {
        if (PipeInfoHelper.ourInstance != null) {
            PipeInfoHelper.ourInstance.close();
        }
    }

    public void close() {
        databaseHelper.close();
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
        ourInstance = null;
    }

    public int addPipe(PipeInfo pipeinfo) throws SQLException {
        // add pipe --  first query if exist in da
        //pipeinfo.
        List<PipeInfo> infos =  mPipeInfoDao.queryForEq("pipeid",pipeinfo.getPipeid());
        for (int i = 0; i < infos.size(); i++) {
            // -- sql delete history items.
            PipeInfo info = infos.get(i);
            Log.e("PipeInfoHelper",info.toString());
            mPipeInfoDao.delete(info);
        }
Log.e("PipeInfoHelper","----------------------------addPipe------"+pipeinfo.getPipeid());
        return mPipeInfoDao.create(pipeinfo);
    }

    public int updatePipe(PipeInfo pipeinfo) throws SQLException {
        return mPipeInfoDao.update(pipeinfo);
    }

    public void deleteAllPipe() throws SQLException {
        mPipeInfoDao.delete(mPipeInfoDao.queryForAll());
    }

    public void delete(PipeInfo pipeInfo) throws SQLException {
        mPipeInfoDao.delete(pipeInfo);
    }

    public List<PipeInfo> queryAll() throws SQLException {
        return mPipeInfoDao.queryForAll();
    }

    public PipeInfo queryById(int id) throws SQLException {
        return mPipeInfoDao.queryForId(id);
    }

    public static void setmContext(Context mContext) {
        PipeInfoHelper.mContext = mContext;
    }
}
